package file;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

import core.Lines;
import core.Point3D;
import core.VectorialObject;

public class LeitorArquivoIsra {
	
	private static final int LENDO_LINHAS = 0;
	
	private static final int LENDO_PONTOS = 1;

	public static VectorialObject parse(File f) throws IOException {
		BufferedReader reader = new BufferedReader(new FileReader(f));
		
		Lines obj = new Lines();
		
		String line = null;

		int status = -1;
		
		while( (line = reader.readLine()) != null ) {
		
			if(line.equals("")) {
			} else if(line.equalsIgnoreCase("PONTOS")) {
				status = LENDO_PONTOS;
			} else if(line.equalsIgnoreCase("LINHAS")) {
				status = LENDO_LINHAS;
			} else {
				switch(status) {
				case LENDO_PONTOS:
					obj.addVertice(parsePonto(line));
					break;
				case LENDO_LINHAS:
					StringTokenizer tokens = new StringTokenizer(line,",");
					while(tokens.hasMoreTokens()){
						StringTokenizer tokenizer = new StringTokenizer(tokens.nextToken());
						Color cor = parseColor(tokenizer.nextToken());
						obj.join(parseLinha(tokenizer), cor);
					}
					break;
				}
			}
		}
		
		return obj;
	}
	
	private static Point3D parsePonto(String line) {
		int x, y, z;
		
		StringTokenizer tokenizer = new StringTokenizer(line);
		
		tokenizer.nextToken();
		
		x = Integer.parseInt(tokenizer.nextToken());
		y = Integer.parseInt(tokenizer.nextToken());
		z = Integer.parseInt(tokenizer.nextToken());
		
		return new Point3D(x, y, z);
	}
	
	private static int[] parseLinha(StringTokenizer tokenizer) {
	
		int indiceP1, indiceP2;
		
		int[] indices = new int[2]; 
	
		indiceP1 = retiraInicial(tokenizer.nextToken());
		indiceP2 = retiraInicial(tokenizer.nextToken());
		
		indices[0] = indiceP1 - 1;
		indices[1]= indiceP2 - 1;
		
		return indices;
	}
	
	private static Color parseColor(String color) {
		String str = color.substring(1);
		
		int intColor = 0;
		
		if(str.startsWith("0x")) {
			str = str.substring(2);
			intColor = Integer.parseInt(str,16);
		}
		else {
			intColor = Integer.parseInt(str);
		}
		
		return new Color(intColor);
	}

	private static int retiraInicial(String strPtr) {
		String str = strPtr.substring(1);
		return Integer.parseInt(str);
	}
}
